<template>
  <div class="page-group-activity">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="test-form"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            :label="$t('product.prodName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.prodName"
              clearable
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('groups.eventName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.activityName"
              clearable
              :placeholder="$t('groups.eventName')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('group.actStatus') + ':'"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.status"
              clearable
              :placeholder="$t('group.actStatus')"
              @change="handleStatusChange"
            >
              <el-option
                :label="$t('group.startUsing')"
                :value="1"
              />
              <el-option
                :label="$t('groups.expired')"
                :value="0"
              />
              <el-option
                :label="$t('groups.notEnabled')"
                :value="2"
              />
              <el-option
                :label="$t('groups.over')"
                :value="5"
              />
              <el-option
                :label="$t('groups.offlineViolation')"
                :value="3"
              />
              <el-option
                :label="$t('groups.moderated')"
                :value="4"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="searchChange(true)"
            >
              {{ $t('shopFeature.searchBar.search') }}
            </div>
            <div
              class="default-btn"
              @click="clearSearch"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 搜索栏end -->
    <!-- 表格主体 -->
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('group:activity:save')"
          class="default-btn primary-btn"
          @click="addOrUpdateHandle()"
        >
          {{ $t("groups.newJoinGroupActivity") }}
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con prod-table">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            fixed
            prop="activityName"
            :label="$t('groups.eventName')"
            min-width="240"
          >
            <template #default="scope">
              <div>
                <span class="table-cell-text line-clamp-one">{{ scope.row.activityName }}</span>
              </div>
            </template>
          </el-table-column>

          <!-- 商品信息 -->
          <el-table-column
            fixed
            :label="$t('product.prodInfo')"
            min-width="240"
          >
            <template #default="{ row }">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow :src="row.pic" />
                </div>
                <span class="table-cell-text">{{ row.prodName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="groupNumber"
            :label="$t('group.groupType')"
            min-width="150"
          >
            <template #default="scope">
              <div>{{ scope.row.groupNumber }}{{ $t('groups.groupOfPeople') }}</div>
            </template>
          </el-table-column>

          <el-table-column
            prop="startTime"
            :label="$t('group.actStartTime')"
            min-width="230"
          />

          <el-table-column
            prop="endTime"
            :label="$t('group.actEndTime')"
            min-width="230"
          />

          <el-table-column
            prop="groupOrderCount"
            :label="$t('group.groupOrderCount')"
            min-width="230"
            sortable
          />

          <el-table-column
            prop="status"
            :label="$t('group.actStatus')"
            min-width="150"
          >
            <template #default="scope">
              <div class="tag-text">
                {{ [$t("groups.expired"), $t("group.startUsing"), $t("groups.notEnabled"),
                    $t('groups.offlineViolation'), $t('groups.moderated'), $t('groups.over')
                ]
                  [scope.row.status] }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            min-width="220"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="scope.row.status === 2"
                  class="default-btn text-btn"
                  @click="activeGroupActivity(scope.row.groupActivityId)"
                >
                  {{ $t('groups.startUsing') }}
                </div>

                <div
                  v-if="isAuth('group:activity:update')"
                  class="default-btn text-btn"
                  @click="addOrUpdateHandle(scope.row.groupActivityId)"
                >
                  {{ scope.row.status === 5 || scope.row.status === 0 ? $t('live.view') : $t('groups.editEvent') }}
                </div>

                <!-- <div class="default-btn text-btn"
            v-if="isAuth('group:activity:manage')"
            @click="manageGroupProdHandle(scope.row.groupActivityId)">{{$t('groups.manageEventProducts')}}</div> -->
                <div
                  v-if="scope.row.status === 1"
                  class="default-btn text-btn"
                  @click="invalidActivityHandle(scope.row)"
                >
                  {{ $t('groups.invalidActivity') }}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="$t('groups.failureTip')"
                    placement="right"
                  >
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
                <!-- :class="[!((scope.row.activityStatus === 1 && scope.row.status !== 1) || (scope.row.activityStatus >= 3 && scope.row.activityStatus <= 6))?'disabled-btn':'','default-btn text-btn']" -->
                <div
                  v-if="isAuth('group:activity:delete')"
                  :class="[!(scope.row.status !== 1) ? 'disabled-btn' : '', 'default-btn text-btn']"
                  @click="deleteHandle(scope.row)"
                >
                  {{ $t('text.delBtn') }}
                </div>
                <div
                  v-if="isAuth('group:activity:auditApply') && scope.row.status > 2 && scope.row.status < 5"
                  class="default-btn text-btn"
                  @click="auditEventHandle(scope.row.groupActivityId)"
                >
                  {{ scope.row.status === 3 ? $t('groups.applyForListing') : $t('coupon.waitReview') }}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="$t('groups.ifNotDealtWith')"
                    placement="right"
                  >
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 表格主体end -->

    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
      @close-add-or-update="closeAddOrUpdate"
    />
    <!-- 下线管理弹窗-->
    <offline-event-handle
      v-if="offlineEventHandleVisible"
      ref="offlineEventRef"
      select-url="/group/activity/getOfflineHandleEventByActivityId"
      apply-url="/group/activity/auditApply"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils/index.js'
import AddOrUpdate from './components/add-or-update.vue'
import offlineEventHandle from '@/components/offline-event-handle/index.vue'

const Data = reactive({
  theData: null, // 保存上次点击查询的请求条件
  dataList: [],
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  // 头部搜索表单
  searchForm: {
    activityName: '',
    status: '',
    prodName: ''
  },
  dataListLoading: false,
  offlineEventHandleVisible: false,
  addOrUpdateVisible: false,
  activeName: ''
})

const { dataList, page, searchForm, offlineEventHandleVisible, addOrUpdateVisible } = toRefs(Data)

onMounted(() => {
  handleClick({ name: '0' })
})

const handleStatusChange = (val) => {
  Data.activeName = val === '' ? '0' : (val > 0 ? val : val === 0 ? -1 : val) + ''
  getDataList()
}

const handleClick = (tab) => {
  const searchObj = JSON.parse(JSON.stringify(Data.searchForm))
  searchObj.status = tab.name === '0' ? '' : tab.name === '-1' ? '0' : tab.name
  getDataList(null, searchObj)
}

const getDataList = (page, searchForm, newData = false) => {
  if (Data.page) {
    const size = Math.ceil(Data.page.total / Data.page.pageSize)
    Data.page.currentPage = (Data.page.currentPage > size ? size : Data.page.currentPage) || 1
  }
  Data.dataListLoading = true
  if (newData || !Data.theData) {
    Data.theData = JSON.parse(JSON.stringify(searchForm || Data.searchForm))
  }
  // eslint-disable-next-line no-unused-expressions
  searchForm ? Data.theData.status = searchForm.status : null
  // console.log(searchForm)
  http({
    url: http.adornUrl('/group/activity/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: page == null ? Data.page.currentPage : page.currentPage,
          size: page == null ? Data.page.pageSize : page.pageSize
        },
        Data.theData
      )
    )
  }).then(({ data }) => {
    const form = searchForm || Data.searchForm
    if (form.status !== null) {
      Data.searchForm.status = form.status === '' ? null : Number(form.status)
    }
    Data.dataList = data.records
    Data.page.total = data.total
    Data.dataListLoading = false
  })
}

const addOrUpdateRef = ref()
// 新增 / 修改
const addOrUpdateHandle = (id) => {
  Data.addOrUpdateVisible = true
  nextTick(() => {
    addOrUpdateRef.value.init(id)
  })
}

const deleteHandle = (row) => {
  if (!(row.status !== 1)) {
    return
  }
  const ids = row ? [row] : Data.dataListSelections.map(item => {
    return item.groupActivityId
  })
  ElMessageBox.confirm($t('groups.confirmDelete') + row.activityName + $t('groups.active'), $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/group/activity/' + row.groupActivityId),
      method: 'delete',
      data: http.adornData({})
    }).then(() => {
      Data.page.total = Data.page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  }).catch(() => {
  })
}

const closeAddOrUpdate = () => {
  Data.addOrUpdateVisible = false
}

const router = useRouter()
/**
 * 刷新回调
 */
const refreshChange = (isRouteToGroupProd, groupActivityId) => {
  Data.addOrUpdateVisible = false
  if (isRouteToGroupProd === 1) {
    router.push({
      path: '/group-groupProd',
      query: { activityId: groupActivityId }
    })
  }
  getDataList(Data.page)
}

// 点击搜索
const searchChange = (newData = false) => {
  Data.page.currentPage = 1
  Data.page.pageSize = 10
  if (Data.searchForm.status !== null) {
    Data.activeName = Data.searchForm.status === '' ? '0' : Data.searchForm.status === 0 ? '-1' : Data.searchForm.status + ''
  }
  getDataList(Data.page, null, newData)
}

const clearSearch = () => {
  Data.searchForm.activityName = ''
  Data.searchForm.status = ''
  Data.searchForm.prodName = ''
}

// 失效活动活动
const invalidActivityHandle = (row) => {
  ElMessageBox.confirm($t('groups.determinedToFail') + row.activityName + $t('groups.actTip'), $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/group/activity/invalid/' + row.groupActivityId),
      method: 'PUT',
      data: http.adornData({})
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(Data.page)
        }
      })
    })
  }).catch(() => {
  })
}

// 启用拼团活动
const activeGroupActivity = (groupActivityId) => {
  http({
    url: http.adornUrl('/group/activity/active/' + groupActivityId),
    method: 'PUT',
    data: http.adornData({})
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        getDataList(Data.page)
      }
    })
  })
}

const offlineEventRef = ref()
// 下线管理
const auditEventHandle = (id) => {
  Data.offlineEventHandleVisible = true
  nextTick(() => {
    offlineEventRef.value.init(id)
  })
}

// 每页数量变更
const handleSizeChange = (val) => {
  Data.page.pageSize = val
  getDataList()
}

// 页数变更
const handleCurrentChange = (val) => {
  Data.page.currentPage = val
  getDataList()
}
</script>

<style lang="scss" scoped></style>
